axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'
const tb = document.querySelector('#tb')
const form = document.querySelector('#bookForm')
const btn1 = document.querySelector('#btnAdd')
const btn2 = document.querySelector('#btnAdd2')
function renderBooks() {
  axios.get('/api/getbooks').then(({ data: res }) => {
    const { data } = res
    tb.innerHTML = data.map(item => {
      return `
      <tr>
        <td>${item.id}</td>
        <td>${item.bookname}</td>
        <td>${item.author}</td>
        <td>${item.publisher}</td>
        <td><a href="#" data-id="${item.id}">删除</a></td>
      </tr>
      `
    }).join('')
  })
}
renderBooks()
btn1.addEventListener('click', function (e) {
  e.preventDefault()
  axios.post('/api/addbook', serialize(form, { hash: false })).then(({ data: res }) => {
    console.log(res)
    if (res.status !== 201) alert(res.msg)
    renderBooks()
  })
})
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    const id = e.target.dataset.id
    axios.get('/api/delbook', {
      params: {
        id
      }
    }).then(() => {
      renderBooks()
    })
  }
})

btn2.addEventListener('click', function () {
    const data = serialize(form)
    console.log(data)
    if (!data) return alert('筛选不能为空')
    axios.get('/api/getbooks?' + data).then(({ data: { data } }) => {
        if (!data.length) {
            render()
            return alert('没有该图书，请重新输入')
        }
        renderBooks(data)
    })
})
